-- 功能：开关灯/门
-- 作者：南风未起
-- 贡献：luatOS && kicad
PROJECT = "air640w-luatos-kicad"
VERSION = "1.0.0"

_G.sys = require("sys")
_G.mqtt2 = require("mqtt2")
_G.mine = require("my_demo")

print(_VERSION)

if wlan ~= nil then
    log.info("mac", wlan.get_mac())
    local ssid = mine.wifi_ssid
    local password = mine.wifi_passwd
    wlan.connect(ssid, password) -- 直连
else
    log.info("警告！", "未连接WiFi")
end

function My_PWM(led1, led2)
    log.info("pwm控制", led1, led2)
    if led1 == "on" then
        --调试代码，调试请保留注释代码
        -- pwm.open(5, 200, led2)
        -- sys.wait(1000)
        pwm.open(5, 200, 45)
        sys.wait(1000)
    end
    if led1 == "off" then
        pwm.open(5, 200, 25)
        sys.wait(1000)
    end
end

function My_mqtt()
    --mqtt域名，端口号，mac/imei
    local host, port, clientId = "mqtt.nfwq666ya.cn", 1883, wlan.getMac():lower()
    --id转为大写，与app扫码的topic一致
    local clientId = string.upper(clientId)
    --注：topic统一为 /luatos/+ imei or mac
    --与uniapp一致
    local topic_req = string.format("/luatos/%s", clientId)
    log.info("topic", topic_req)
    local sub_topics = {}
    sub_topics[topic_req] = 1
    _G.mqttc =
        mqtt2.new(
        clientId,
        300,
        "",
        "",
        1,
        host,
        port,
        sub_topics,
        function(pkg)
            --{"led1":"on","led2":34}//调试舵机的角度
            mydata = json.decode(pkg.payload)
            if mydata == nil then
                led1, led2 = "off", 0
            else
                led1 = mydata["led1"]
                led2 = mydata["led2"]
            end
            ---pwm控制函数
            My_PWM(led1, led2)
        end,
        "mqtt_airm2m"
    )
    while not socket.isReady() do
        sys.waitUntil("NET_READY", 1000)
    end
    sys.wait(1000)
    log.info("go", "GoGoGo")
    mqttc:run() -- 会一直阻塞在这里
end
sys.taskInit(
    function()
        while 1 do
            --执行业务函数
            My_mqtt()
        end
    end
)
sys.run()
